<?php
namespace App\Http\Controllers;

use App\Model\NewActivity;
use Illuminate\Http\Request;
use DB;
use App\Http\Common;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;


class EventController extends Controller {

	use Common;

    public $current = 'NewActivity';
    public $currentTmp = 'NewActivityTmp';
    public $isAdmin = 0;
    public $adminUserIdArr = [1,117];

    public $eventObj;

	public function __construct(Request $request)
    {

        // $this->middleware('admin', ['only' => [
        //                                         'postCreate',
        //                                         'postUpdate',
        //                                         'postDelete',
        //                                     ]
        //     ]);

        $this->eventObj = new NewActivity();

        $this->middleware('nocacheview', ['only' => [
                                                'getIndex',
                                                'getCreate',
                                                'getUpdate','getUpdatetmp','postUploadfile'
                                            ]
            ]);
    }

    // public function getChange()
    // {
    //     $data = file_get_contents('SchoolName.json');
    //     $data = str_replace(array("\r\n", "\r", "\n"), "", $data);
    //     $data = json_decode($data,true);

    //     foreach($data as $value)
    //     {
    //         $arr = [];
    //         $arr['name_en'] = $value['name_en'];
    //         $arr['name_cn'] = $value['name_cn'];
    //         $arr['country_en'] = $value['country_name_en'];
    //         $arr['country_cn'] = $value['country_name_cn'];
    //         $arr['country_id'] = $value['countryId'];

    //         DB::table('record')->insert($arr);          
    //     }
    //     dd('end');
    // }

	public function getIndex(Request $request)
	{
        $admin = session()->get('adminInfo');
        $this->isAdmin = 0;
        if(in_array($admin->user_id, $this->adminUserIdArr)){
            $this->isAdmin = 1;
        }
        $data = $this->eventObj->getList($admin->user_id, $this->isAdmin);
//        echo 'ad<Pre>';print_r($data);die();

		return view('event.index', ['data' => $data, 'current' => $this->current, 'isAdmin' => $this->isAdmin]);
	}

    public function getTmp(Request $request)
    {
        $admin = session()->get('adminInfo');
        $isAdmin = 0;
        if(in_array($admin->user_id, $this->adminUserIdArr)){
            $this->isAdmin = 1;
            $isAdmin = 1;
        }
        $data = $this->eventObj->getListTmp($admin->user_id, $this->isAdmin);
//        echo 'ad<Pre>';print_r($data);die();

        return view('event.indextmp', ['data' => $data,
            'current' => $this->currentTmp,
            'imgUrl' => $this->getImgUrl(),
            'isAdmin' => $isAdmin,
        ]);
    }
    
    public function getCreate()
    {
        $admin = session()->get('adminInfo');
        //获取该用户关注的人
//        $followList = $this->eventObj->getUserFollow($admin->user_id);
//        echo 'ad<Pre>';print_r($followList);die();
        return view('event.create', ['current' => $this->currentTmp]);
    }

    /**
     * 创建 未审核 活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postCreate(Request $request)
    {   
        $data = $request->all();
        $admin = session()->get('adminInfo');
        if(empty($data['cover_path'])){
            return $this->errorReturn('请上传图片');
        }
        $eventData['cover_path'] = $data['cover_path'];
        $eventData['title'] = $data['title'];
        $eventData['description'] = $data['description'];
        $eventData['create_time'] = strtotime($data['create_time']);
        $eventData['end_time'] = strtotime($data['end_time']);
        $eventData['address'] = $data['address'];
        $eventData['is_public'] = $data['is_public'];
        $eventData['is_free'] = $data['is_free'];
        $eventData['user_id'] = $admin->user_id;
        $eventData['status'] = 0;    //待审核状态
//        Redis::set($admin->user_id, json_encode($data['join']));
//        echo Redis::get($admin->user_id).'<pre>';print_r($data);die();
        //添加状态
//        $data['status'] = 1;

        if(0 == $data['is_free']){
            if(empty($data['ticket_eb']['price']) && empty($data['ticket_eb_f']['price'])
            && empty($data['ticket_mb']['price']) && empty($data['ticket_mb_f']['price']))
            return $this->errorReturn('请填写收费信息');
        }
        $eventId = $this->eventObj->create($eventData);
        if($eventId > 0){
            //收费活动，需要填写票子信息
            if(0 == $data['is_free']){
                $time = time();
                //1会员0非会员,2早鸟会员价,3早鸟非会员价
                //早鸟会员价
                if(!empty($data['ticket_eb']['price'])){
                    $data['ticket_eb']['title'] = '早鸟会员价';
                    $this->fillTicketDataTmp($data['ticket_eb'], $eventId, $time, 1);
                }
                //早鸟非会员价
                if(!empty($data['ticket_eb_f']['price'])){
                    $data['ticket_eb_f']['title'] = '早鸟非会员价';
                    $this->fillTicketDataTmp($data['ticket_eb_f'], $eventId, $time, 0);
                }
                //会员价
                if(!empty($data['ticket_mb']['price'])){
                    $data['ticket_mb']['title'] = '会员价';
                    $this->fillTicketDataTmp($data['ticket_mb'], $eventId, $time, 1);
                }
                //非会员价
                if(!empty($data['ticket_mb_f']['price'])){
                    $data['ticket_mb_f']['title'] = '非会员价';
                    $this->fillTicketDataTmp($data['ticket_mb_f'], $eventId, $time, 0);
                }
            }
            //邀请的会员，写入redis
//            if(isset($data['join']) && !empty($data['join'])){
//                Redis::set($admin->user_id.'_'.$eventId, json_encode($data['join']));
//            }
        }else{
            return $this->errorReturn('创建失败');
        }

        return $this->successReturn('创建成功');
    }

    /**
     * 填充票子信息
     * @param $data
     * @param $eventId
     * @param $time
     * @param $isMember
     * @param $earlyBird
     * @param $earlyBirdDeadline
     * @return mixed
     */
    private function fillTicketDataTmp($data, $eventId, $time, $isMember)
    {
        $ticketData['title'] = $data['title'];
        $ticketData['name'] = $data['name'];
        $ticketData['price'] = $data['price'];
        $ticketData['currency'] = $data['currency'];
        $ticketData['object_id'] = $eventId;
        $ticketData['count'] = $data['count'];
        $ticketData['create_time'] = $time;
        $ticketData['is_member'] = $isMember;
        $ticketData['early_bird_deadline'] = isset($data['early_bird_deadline'])?strtotime($data['early_bird_deadline']):'';
        $ticketData['status'] = 1;
        $this->eventObj->createTicketTmp($ticketData);
        return;
    }

    /**
     * 填充票子信息
     * @param $data
     * @param $eventId
     * @param $time
     * @param $isMember
     * @param $earlyBird
     * @param $earlyBirdDeadline
     * @return mixed
     */
    private function fillTicketData($data, $eventId)
    {
        $ticketData['title'] = $data['title'];
        $ticketData['name'] = $data['name'];
        $ticketData['price'] = $data['price'];
        $ticketData['currency'] = $data['currency'];
        $ticketData['object_id'] = $eventId;
        $ticketData['count'] = $data['count'];
        $ticketData['create_time'] = $data['create_time'];
        $ticketData['is_member'] = $data['is_member'];
        $ticketData['early_bird_deadline'] = $data['early_bird_deadline'];
        $ticketData['status'] = 1;
        $this->eventObj->createTicket($ticketData);
        return;
    }

    /**
     * 更新 未审核活动的票子信息
     * @param $data
     * @param $eventId
     * @param $time
     * @param $isMember
     */
    private function updateTicketDataTmp($data, $eventId, $time, $isMember)
    {
        $ticketData['name'] = $data['name'];
        $ticketData['title'] = $data['title'];
        $ticketData['price'] = $data['price'];
        $ticketData['currency'] = $data['currency'];
        $ticketData['object_id'] = $eventId;
        $ticketData['count'] = $data['count'];
        $ticketData['create_time'] = $time;
        $ticketData['is_member'] = $isMember;
        $ticketData['early_bird_deadline'] = isset($data['early_bird_deadline'])?strtotime($data['early_bird_deadline']):'';
        $ticketData['status'] = 1;
        $this->eventObj->updateTicketTmp($ticketData, $eventId);
        return;
    }

    /**
     * 更新 已审核活动的票子信息
     * @param $data
     * @param $eventId
     * @param $time
     * @param $isMember
     */
    private function updateTicketData($data, $eventId, $time, $isMember)
    {
        $ticketData['name'] = $data['name'];
        $ticketData['title'] = $data['title'];
        $ticketData['price'] = $data['price'];
        $ticketData['currency'] = $data['currency'];
        $ticketData['object_id'] = $eventId;
        $ticketData['count'] = $data['count'];
        $ticketData['create_time'] = $time;
        $ticketData['is_member'] = $isMember;
        $ticketData['early_bird_deadline'] = isset($data['early_bird_deadline'])?strtotime($data['early_bird_deadline']):'';
        $ticketData['status'] = 1;
        $this->eventObj->updateTicket($ticketData, $eventId);
        return;
    }

    /**
     * 如果票子的票价为空，则判断是否需要删除原有的
     * @param $data
     * @param $eventId
     */
    private function deleteTicketDataTmp($data, $eventId)
    {
        $this->eventObj->deleteTicketTmp($data, $eventId);
        return;
    }

    /**
     * 如果票子的票价为空，则判断是否需要删除原有的
     * @param $data
     * @param $eventId
     */
    private function deleteTicketData($data, $eventId)
    {
        $this->eventObj->deleteTicket($data, $eventId);
        return;
    }

    public function getUpdate(Request $request)
    {
        $req = $request->all();
        $id = $req['id'];
        $admin = session()->get('adminInfo');
        if(!in_array($admin->user_id, $this->adminUserIdArr)){
            return Redirect::to('event');
        }
        $data = $this->eventObj->getInfoById($id);
        if(empty($data)){
            return Redirect::to('event');
//            return $this->errorReturn('该活动不存在');
        }
        $data->cover_path_src = $this->getImgUrl().$data->cover_path.'?imageMogr2/format/jpg';
        $data->start_time = date('Y-m-d H:i:s', $data->start_time);
        $data->end_time = date('Y-m-d H:i:s', $data->end_time);
        $data->publicSelect = [
            ['id' => 1, 'name' => '公开活动'],
//            ['id' => 0, 'name' => '私密活动'],
        ];
        $data->freeSelect = [
//            ['id' => 1, 'name' => '免费'],
            ['id' => 0, 'name' => '收费'],
        ];
        $data->statusSelect = [
            ['id' => 1, 'name' => '在线'],
            ['id' => 0, 'name' => '下线'],
        ];
        //读取票子
        $data->ticket = '';
        if(0 == $data->is_free){
            $ticketRet = $this->eventObj->getTicketByEventId($id);
            $data->ticket = $ticketRet;
            $data->currencySelect = $this->getCurrencyArr();
            foreach($ticketRet as &$val){
                if($val->early_bird_deadline > 0){
                    $val->early_bird_deadline = date('Y-m-d H:i', $val->early_bird_deadline);
                }
                if(0 == $val->is_member){
                    if(('非会员价' == $val->title) && (1 == $val->status)){//非会员
                        $data->ticket['ticket_mb_f'] = $val;
                    }elseif(('早鸟非会员价' == $val->title) && (1 == $val->status)){//早鸟非会员价
                        $data->ticket['ticket_eb_f'] = $val;
                    }
                }elseif(1 == $val->is_member){
                    if(('会员价' == $val->title) && (1 == $val->status)){//会员
                        $data->ticket['ticket_mb'] = $val;
                    }elseif(('早鸟会员价' == $val->title) && (1 == $val->status)){//早鸟会员价
                        $data->ticket['ticket_eb'] = $val;
                    }
                }
            }
        }
//        echo '<Pre>';print_r($data);die();

        return view('event.update', [
            'current' => $this->current,
            'data' => $data,
//            'userFollowList' => $userFollowList,
//            'followList' => $followList
        ]);
    }

    /**
     * 修改页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function getUpdatetmp(Request $request)
    {
        $req = $request->all();
        $id = $req['id'];
        $admin = session()->get('adminInfo');
        if(in_array($admin->user_id, $this->adminUserIdArr)){
            $data = $this->eventObj->getInfoByAdmin($id);
        }else{
            $data = $this->eventObj->getInfoByIdTmp($id, $admin->user_id);
        }
        if(empty($data)){
            return Redirect::to('event/tmp');
//            return $this->errorReturn('该活动不存在');
        }
        $data->cover_path_src = $this->getImgUrl().$data->cover_path.'?imageMogr2/format/jpg';
        $data->create_time = date('Y-m-d H:i:s', $data->create_time);
        $data->end_time = date('Y-m-d H:i:s', $data->end_time);
        $data->publicSelect = [
            ['id' => 1, 'name' => '公开活动'],
            ['id' => 0, 'name' => '私密活动'],
        ];
        $data->freeSelect = [
            ['id' => 1, 'name' => '免费'],
            ['id' => 0, 'name' => '收费'],
        ];
        $data->statusSelect = [
            ['id' => 1, 'name' => '在线'],
            ['id' => 0, 'name' => '下线'],
        ];
        //读取票子
        $data->ticket = '';
        if(0 == $data->is_free){
            $ticketRet = $this->eventObj->getTicketTmpByEventId($id);
            $data->ticket = $ticketRet;
            $data->currencySelect = $this->getCurrencyArr();
            foreach($ticketRet as &$val){
                if($val->early_bird_deadline > 0){
                    $val->early_bird_deadline = date('Y-m-d H:i', $val->early_bird_deadline);
                }
                if(0 == $val->is_member){
                    if(('非会员价' == $val->title) && (1 == $val->status)){//非会员
                        $data->ticket['ticket_mb_f'] = $val;
                    }elseif(('早鸟非会员价' == $val->title) && (1 == $val->status)){//早鸟非会员价
                        $data->ticket['ticket_eb_f'] = $val;
                    }
                }elseif(1 == $val->is_member){
                    if(('会员价' == $val->title) && (1 == $val->status)){//会员
                        $data->ticket['ticket_mb'] = $val;
                    }elseif(('早鸟会员价' == $val->title) && (1 == $val->status)){//早鸟会员价
                        $data->ticket['ticket_eb'] = $val;
                    }
                }
            }
        }
        $data->isAdmin = 0;
        if(in_array($admin->user_id, $this->adminUserIdArr)){
            $data->isAdmin = 1;
        }
        //获取该用户关注的人
//        $followList = $this->eventObj->getUserFollow($admin->user_id);
//        $userFollowList = Redis::get($admin->user_id.'_'.$id);
//        echo '<Pre>';print_r($data);die();

        return view('event.updatetmp', [
            'current' => $this->currentTmp,
            'data' => $data,
//            'userFollowList' => $userFollowList,
//            'followList' => $followList
        ]);
    }

    /**
     * 管理员修改活动信息
     * @param Request $request
     * @return mixed
     */
    public function postUpdate(Request $request)
    {
        $data = $request->all();
        $admin = session()->get('adminInfo');
        if(!empty($data['cover_path'])){
            $eventData['cover_path'] = $data['cover_path'];
        }
        $eventData['title'] = $data['title'];
        $eventData['description'] = $data['description'];
        $eventData['start_time'] = strtotime($data['start_time']);
        $eventData['end_time'] = strtotime($data['end_time']);
        $eventData['address'] = $data['address'];
//        echo '<Pre>';print_r($data);die();

        $id = $data['id'];

        unset($data['id']);

        $rs = $this->eventObj->update($eventData, $id);
        //收费活动，需要填写票子信息
        if(0 == $data['is_free']){
            $time = time();
            //1会员0非会员,2早鸟会员价,3早鸟非会员价
            //早鸟会员价
            if(!empty($data['ticket_eb']['price'])){
                $data['ticket_eb']['title'] = '早鸟会员价';
                $this->updateTicketData($data['ticket_eb'], $id, $time, 1);
            }else{
                $data['ticket_eb']['title'] = '早鸟会员价';
                $this->deleteTicketData($data['ticket_eb'], $id);
            }
            //早鸟非会员价
            if(!empty($data['ticket_eb_f']['price'])){
                $data['ticket_eb_f']['title'] = '早鸟非会员价';
                $this->updateTicketData($data['ticket_eb_f'], $id, $time, 0);
            }else{
                $data['ticket_eb_f']['title'] = '早鸟非会员价';
                $this->deleteTicketData($data['ticket_eb_f'], $id);
            }
            //会员价
            if(!empty($data['ticket_mb']['price'])){
                $data['ticket_mb']['title'] = '会员价';
                $this->updateTicketData($data['ticket_mb'], $id, $time, 1);
            }else{
                $data['ticket_mb']['title'] = '会员价';
                $this->deleteTicketData($data['ticket_mb'], $id);
            }
            //非会员价
            if(!empty($data['ticket_mb_f']['price'])){
                $data['ticket_mb_f']['title'] = '非会员价';
                $this->updateTicketData($data['ticket_mb_f'], $id, $time, 0);
            }else{
                $data['ticket_mb_f']['title'] = '非会员价';
                $this->deleteTicketData($data['ticket_mb_f'], $id);
            }
        }
//        echo '<Pre>';print_r($rs);die();

        return $this->successReturn('更新成功');
    }

    /**
     * 修改提交
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUpdatetmp(Request $request)
    {
        $data = $request->all();
        $admin = session()->get('adminInfo');
        if(!empty($data['cover_path'])){
            $eventData['cover_path'] = $data['cover_path'];
        }
        $eventData['title'] = $data['title'];
        $eventData['description'] = $data['description'];
        $eventData['create_time'] = strtotime($data['create_time']);
        $eventData['end_time'] = strtotime($data['end_time']);
        $eventData['address'] = $data['address'];
        $eventData['is_public'] = $data['is_public'];
        $eventData['is_free'] = $data['is_free'];
        $eventData['user_id'] = $admin->user_id;
        $eventData['status'] = 0;    //待审核状态
//        echo '<Pre>';print_r($data);die();

        $id = $data['id'];

        unset($data['id']);

        $rs = $this->eventObj->updatetmp($eventData, $id);
        //收费活动，需要填写票子信息
        if(0 == $eventData['is_free']){
            $time = time();
            //1会员0非会员,2早鸟会员价,3早鸟非会员价
            //早鸟会员价
            if(!empty($data['ticket_eb']['price'])){
                $data['ticket_eb']['title'] = '早鸟会员价';
                $this->updateTicketDataTmp($data['ticket_eb'], $id, $time, 1);
            }else{
                $data['ticket_eb']['title'] = '早鸟会员价';
                $this->deleteTicketDataTmp($data['ticket_eb'], $id);
            }
            //早鸟非会员价
            if(!empty($data['ticket_eb_f']['price'])){
                $data['ticket_eb_f']['title'] = '早鸟非会员价';
                $this->updateTicketDataTmp($data['ticket_eb_f'], $id, $time, 0);
            }else{
                $data['ticket_eb_f']['title'] = '早鸟非会员价';
                $this->deleteTicketDataTmp($data['ticket_eb_f'], $id);
            }
            //会员价
            if(!empty($data['ticket_mb']['price'])){
                $data['ticket_mb']['title'] = '会员价';
                $this->updateTicketDataTmp($data['ticket_mb'], $id, $time, 1);
            }else{
                $data['ticket_mb']['title'] = '会员价';
                $this->deleteTicketDataTmp($data['ticket_mb'], $id);
            }
            //非会员价
            if(!empty($data['ticket_mb_f']['price'])){
                $data['ticket_mb_f']['title'] = '非会员价';
                $this->updateTicketDataTmp($data['ticket_mb_f'], $id, $time, 0);
            }else{
                $data['ticket_mb_f']['title'] = '非会员价';
                $this->deleteTicketDataTmp($data['ticket_mb_f'], $id);
            }
        }
//        echo '<Pre>';print_r($rs);die();

        return $this->successReturn('更新成功');
    }

    /**
     * 管理员操作下线
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postOffline(Request $request)
    {
        $id = $request->input('id');
        $this->eventObj->doOffline($id);
        return $this->successReturn('成功下线');
    }

    /**
     * 管理员操作上线
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postOnline(Request $request)
    {
        $id = $request->input('id');
        $this->eventObj->doOnline($id);
        return $this->successReturn('成功上线');
    }

    public function postDelete(Request $request)
    {
        $id = $request->input('id');

        $rs = $this->recordObj->delete($id);

        return $this->successReturn('删除成功');
    }

    public function postDeletetmp(Request $request)
    {
        $id = $request->input('id');

        $rs = $this->eventObj->deletetmp($id);

        return $this->successReturn('删除成功');
    }

    public function postUploadfile(Request $request)
    {
//        echo '<Pre>';print_r($_FILES);die();
        $image = $_FILES['pics']['tmp_name'];
        if(!empty($image)){
            $appEnv = $this->getAppEnv();
            //保存地址
            if('dev' == $appEnv){
                //开发环境
                $save_path = public_path().'/image';
            }elseif('test' == $appEnv){
                //测试环境，123.59.78.184
                $save_path = '/data/image';
            }
            else{
                //生产环境
                $save_path = '/nfs/images';
            }
            $date = date('Ymd', time());
            $save_path .= '/'.$date;
            if (!file_exists($save_path)) {
                mkdir($save_path, 0777, true);
            }else{
//                chmod($save_path, 0777);
            }
            $isBreak = 0;
//            echo '<Pre>';print_r($image);die();
//            echo $appEnv.' '.$save_path;die();
            foreach($image as $key => $val){
                $fp = fopen($val, 'r');
                $file = fread($fp, $_FILES['pics']['size'][$key]);  //二进制数据流
                $imgSuffix = str_replace('image/', '', $_FILES['pics']['type'][$key]); //图片后缀名
                //要生成的图片名字
                $filename = time().mt_rand(10, 99).".".$imgSuffix; //新图片名称
                $newFilePath = $save_path.'/'.$filename;
                $data = $file;
                $newFile = fopen($newFilePath,"w"); //打开文件准备写入
                if(fwrite($newFile,$data) === false){//写入二进制流到文件
                    $isBreak = 0;
                }
                fclose($newFile); //关闭文件
            }
            if(!$isBreak){
                return $this->successReturn($date.'/'.$filename);
            }
            return $this->errorReturn('Fail');
        }
        return $this->errorReturn('Fail');
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postReturn(Request $request)
    {
        $data = $request->all();
        $ret = $this->eventObj->updateReturnReason($data);
        if($ret){
            return $this->successReturn('更新成功');
        }
        return $this->errorReturn('更新失败');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postRelease(Request $request)
    {
        $time = time();
        $data = $request->all();
        $ret = $this->eventObj->getInfoByAdmin($data['id']);
        $eventObj = $ret;
        $eventObj->status = 1;
        $eventObj->is_original = 1; //app原生
        $eventObj->start_time = $ret->create_time;
        $eventObj->create_time = $time;
        //获取new_activity_ticket_tmp表中的票子信息
        $ticketTmpList = $this->eventObj->getTicketTmpByEventId($eventObj->id);
//        echo '<pre>';print_r($ticketTmpList);die();
        unset($eventObj->id);
        unset($eventObj->return_reason);
//        echo '<Pre>';print_r($eventObj);die();
        $ret = $this->eventObj->createEvent(get_object_vars($eventObj));
        if($ret){
            //写入 new_all_list 表
            $allListData['user_id'] = $eventObj->user_id;
            $allListData['object_id'] = $ret;
            $allListData['object_type'] = 3;
            $allListData['create_time'] = $time;
            $allListData['status'] = 1;
            $this->eventObj->createAllList($allListData);
            //更新new_activity_tmp表
            $this->eventObj->updatetmp(['status' => 1], $data['id']);
            //把 new_activity_ticket_tmp 表的数据写入 new_activity_ticket
            if(!empty($ticketTmpList)){
                foreach($ticketTmpList as $val){
                    $this->fillTicketData(get_object_vars($val), $ret);
                }
            }
            return $this->successReturn('更新成功');
        }
        return $this->errorReturn('更新失败');
//        echo '<Pre>';print_r(get_object_vars($eventObj));die();
    }

}